package coupon

import (
	"gorm.io/gorm"
	"shop/database/mysql"
)

type PointsCoupon struct {
	gorm.Model
	UserID           int64  `json:"user-id" gorm:"type:int(11);not null"`
	CouponName       string `json:"coupon_name" gorm:"type:varchar(100);comment:优惠卷名称"`
	PointsRequired   int    `json:"points_required" gorm:"type:int(11);comment:兑换积分"`
	CouponNumber     int    `json:"coupon_number" gorm:"type:int(11);comment:优惠卷数量"`
	CouponExpiration int    `json:"coupon_expiration" gorm:"type:int(11);comment:过期天数"`
}

func (p *PointsCoupon) PointsCouponInfo(pointsId int64) (info *PointsCoupon, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("points_coupons").Where("id = ?", pointsId).First(&info).Where("coupon_number > 0").Updates(map[string]interface{}{"coupon_number": gorm.Expr("coupon_number - ?", 1)}).Error
	})
}

func (p *PointsCoupon) PointsList() (info []PointsCoupon, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("points_coupons").Find(&info).Error
	})
}

func (p *PointsCoupon) PointsInfoByID(pointsId int64) (info *PointsCoupon, err error) {
	return info, mysql.WithMysql(func(db *gorm.DB) error {
		return db.Table("points_coupons").Where("id = ?", pointsId).First(&info).Error

	})
}
